<?php

/**
 * 杭州海轶跨境云SDK
 * @author chenyun
 */
namespace App\Service\VendorClient\Shophaiyi;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;
use App\Model\PssModel\ServiceConfig;

class ShophaiyiApiClient
{
    private $account  = 'Shophaiyi';
    protected $config;
    protected $RouteMap = [
        'queryGoodsList'        => 'oms.palletproduct.list',
        'createOrder'           => 'oms.orderPush',
        'cancelOrder'           => 'oms.afterPush',
    ];
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }
    
    /**
     * 创建订单
     */
    public function createOrder( $params = [] ) 
    {   
        ini_set('serialize_precision', 14);
        if( empty($params['supplierOrder']) || empty($params['orderGoods']) || empty($params['order']) || empty($params['binfo']) ) {
            return Normal::returnCode(Normal::FAIL,"except param supplierOrder or orderGoods or order or binfo");
        }
        //组装订单参数
        $orderInfo = $params['supplierOrder'];
        $order     = $params['order'];
        $apply_extends    = [];
        //运费
        $deliver_money  = $orderInfo['deliver_money'];
        //商品下单组
        $skuList = [];
        $productAmt = 0;
        $TaxAmt     = 0;
        foreach ($params['orderGoods'] as $key => $item ) 
        {
            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            //如果商品除不尽，得多取以为，减去实际金额为折扣，折扣不能为负数
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);
            $totalGoods         = bcmul((string)$singleGoodsPrice,(string)$buyAcount,2);

//             //含税税率
//             $tax_rate           = bcadd('1', (string)$item['tax_rate'],4);
//             //不含税价格
//             $not_tax_price      = bcdiv((string)$singleGoodsPrice, (string)$tax_rate,3);
//             // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
//             $not_tax_price      = ceil(bcmul((string)$not_tax_price,(string)'100',1));
//             // echo "含税税率:".$tax_rate."不含税价格：".$not_tax_price;
//             $not_tax_price      = bcdiv((string)$not_tax_price,'100',2);
            
//             //税金
//             $singleGoodsTax     = bcsub((string)$singleGoodsPrice, (string)$not_tax_price,3);
            
//             //单个商品总税金
//             $totalGoodsTax  = bcmul((string)$singleGoodsTax,(string)$buyAcount,2);
            
//             //单个商品总不含税价格
//             $totalGoods     = bcmul((string)$not_tax_price,(string)$buyAcount,2);
            //商品组
            $skuList[] = [
                "goodsIndex"        => $key+1,
                "platformProCode"   => $item['supplier_skucode'],
                "platformProName"   => $item['goods_name'],
                "price"             => (float)$singleGoodsPrice,
                "num"               => $buyAcount,
                "goodsTotalTax"     => 0.00,
            ];
            $productAmt = bcadd((string)$productAmt,(string)$totalGoods,2);
            //$TaxAmt = bcadd((string)$TaxAmt,(string)$totalGoodsTax,2);
        }

        //实际下单金额
        $real_total_money = $orderInfo['real_total_money'];
        //订单总金额 = 含税商品总金额 + 运费 - 优惠金额
        $ActualPaidAmt = bcadd((string)$productAmt,(string)$TaxAmt,2);
        //优惠金额
        $discount_money = bcsub((string)$ActualPaidAmt,(string)$real_total_money,2);
        //下单支付的时候支付信息
        $apply_extends  = @json_decode($orderInfo['apply_extends'],true);
        //支付时间
        $payTime        = empty($order['payTime']) ? $orderInfo['pay_time'] :$order['payTime'];
        //支付时间
        $pay_time       = $payTime ? $payTime : time();
        $pay_time       = date('Y-m-d H:i:s',$pay_time);
        //支付流水号
        $pay_sn         = $order['paySerial'] ?? $orderInfo['pay_sn'];

       //获取上游供应商支付方式路由
        $payCommanyCode = $apply_extends['payCommanyCode'] ?? '';
        $PayCompanyCode = $order['payCommanyCode'] ? $order['payCommanyCode'] : $payCommanyCode;
        $pay_value      = ServiceConfig::instance()->getConfigByEventsValue($this->account, ServiceConfig::TYPE_PAY, $PayCompanyCode);
        if (empty($pay_value)) {
            return Normal::returnCode(Normal::FAIL, "支付公司编码：【{$PayCompanyCode}】未映射，请联系管理员处理");
        } 
        
        //电商平台信息
        $enterpriseNum  = $apply_extends['enterpriseNum'] ?? '';
        $enterpriseName = $apply_extends['enterpriseName'] ?? '';
        $enterpriseNum  = $order['enterpriseNum'] ? $order['enterpriseNum'] : $enterpriseNum;
        $enterpriseName = $order['enterpriseName'] ? $order['enterpriseName'] : $enterpriseName;

        //创建订单数据
        $data = [
            'platformOrderNo'       => $orderInfo['supplier_dsn'],
            'declareNo'             => $orderInfo['supplier_dsn'],
            'orderTime'             => date("Y-m-d H:i:s",$orderInfo['cd']),
            'payTime'               => $pay_time,
            'payNo'                 => $pay_sn,
            'payType'               => $pay_value,
            'buyerId'               => $orderInfo['buyer_phone'],
            'buyerIdno'             => $orderInfo['buyer_idcard'],
            'buyerName'             => $orderInfo['buyer_realname'],
            'buyerPhone'            => $orderInfo['buyer_phone'],
            'consigneeProvince'     => $orderInfo['province'],
            'consigneeCity'         => $orderInfo['city'],
            'consigneeArea'         => $orderInfo['district'],
            'consigneeAddress'      => $orderInfo['receive_address'],
            'consigneeFullAddress'  => $orderInfo['province'].$orderInfo['city'].$orderInfo['district'].$orderInfo['receive_address'],
            'consignee'             => $orderInfo['receive_name'],
            'consigneePhone'        => $orderInfo['recveive_phone'],
            'logisFee'              => 0.00,
            'disFee'                => (float)$discount_money,
            'taxFee'                => (float)$TaxAmt,
            'goodsFee'              => (float)$productAmt,
            'payFee'                => (float)$real_total_money,
            'platformCode'          => '',
            'shopCode'              => '',
            'ebpCode'               => $enterpriseNum,
            'ebpName'               => $enterpriseName,
            'goodsList'             => $skuList
        ];
        $requestParam = [
            'method'    => 'createOrder',
            'data'      => json_encode($data,JSON_UNESCAPED_UNICODE)
        ];
        $res = $this->execute($requestParam);
        return $res;
    }
   
    /**
     * 获取取消订单
     */
    public function cancelOrder( $params = [] ) 
    {
        $orderSupplier = $params['supplierOrder'];
        $orderGoods    = $params['orderGoods'];
        $order         = $params['order'];
        //运费
        $deliver_money = $orderSupplier['deliver_money'];
        $backAmount    = (float)$orderSupplier['real_total_money'];
        $backNum       = 0;
        $goodsList     = [];
        foreach ($orderGoods as $key =>$item){

            //卖价
            $price              = $item['price'];
            //商品购买规格数量
            $spec_num           = $item['spec_num'];
            //商品购买数量(下单数量 X 起售数量)
            $quantity           = $item['quantity'];
            //实际购买数量
            $buyAcount          = $spec_num * $quantity ;
            //如果商品除不尽，得多取以为，减去实际金额为折扣，折扣不能为负数
            if( $key == 0 ) {
                $singleDeliveryMoney = bcdiv((string)$deliver_money,(string)$quantity,3);
                $singleDeliveryMoney = bcmul((string)$singleDeliveryMoney,(string)100,1);
                $singleDeliveryMoney = bcdiv((string)ceil($singleDeliveryMoney), (string)100,2);
                $price               = bcadd((string)$price, (string)$singleDeliveryMoney,2);
            }
            //单个商品价格
            $singleGoodsPrice   = bcdiv((string)$price, (string)$spec_num,3);
            $singleGoodsPrice   = ceil(bcmul((string)$singleGoodsPrice,(string)'100',1));
            $singleGoodsPrice   = bcdiv((string)$singleGoodsPrice,'100',2);

            $backNum+= $buyAcount;
            $goodsList[] = [
                "goodsIndex"        => $key+1,
                "platformProCode"   => $item['supplier_skucode'],
                "platformProName"   => $item['goods_name'],
                "price"             => (float)$singleGoodsPrice,
                "num"               => $buyAcount,
            ];
        }
        $data = [
            'platformOrderNo'   => $orderSupplier['supplier_dsn'],
            'platformAfterNo'   => $orderSupplier['supplier_dsn'],
            'afterState'        => 2,
            'type'              => 1,
            'backAmount'        => $backAmount,
            'backNum'           => $backNum,
            'applyTime'         => date("Y-m-d H:i:s",time()),
            'remark'            => $order["exceptReason"],
            'goodsList'         => $goodsList,
        ];

        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => json_encode($data,JSON_UNESCAPED_UNICODE)
        ];
        $res = $this->execute($requestParam);
        return $res;
        
    }
    /**
     * 查询商品信息
     */
    public function queryGoodsList($param)
    {
        //获取商品列表
        $goodsWhere = [
            'page'      => $param['page']  ?? 1,
            'pageSize'  => 10,
        ];
        $requestParam = [
            'method'    => 'queryGoodsList',
            'data'      => json_encode($goodsWhere,JSON_UNESCAPED_UNICODE),
        ];
        $res  = $this->execute($requestParam);
        if($res["code"] != Normal::SUC or !isset($res["data"]["data"]["dataList"]) or empty($res["data"]["data"]["dataList"])){
            return $res;
        }
        $result_query_goods = $res["data"]["data"]["dataList"];
        $details = [];
        foreach ($result_query_goods as $sku)
        {
            //处理规格数据
            if(!empty($sku['skuList'])){
                foreach ($sku['skuList'] as $skuList){
                    //组装数据
                    $details[]= [
                        'proCode'           => $sku["proCode"],
                        'wareName'          => $sku["wareName"],
                        'prodSecondImgList' => $sku["prodSecondImgList"],
                        'prodIntroInfo'     => $sku["prodIntroInfo"],
                        'proName'           => $sku["proName"],
                        'proGno'            => $sku["proGno"],
                        'proCategoryName'   => $sku["proCategoryName"],
                        'proBrandName'      => $sku["proBrandName"],
                        'proUnitName'       => $sku["proUnitName"],
                        'skuCode'           => $skuList["skuCode"],
                        'skuId'             => $skuList["skuId"],
                        'supplyPrice'       => $skuList["supplyPrice"],
                        'postageFlag'       => $skuList["postageFlag"],
                        'taxFlag'           => $skuList["taxFlag"],
                        'highTaxFlag'       => $skuList["highTaxFlag"],
                        'highTaxRate'       => $skuList["highTaxRate"],
                        'listingStatus'     => $skuList["listingStatus"],
                        'taxRate'           => $skuList["taxRate"],
                        'priceThreshold'    => $skuList["priceThreshold"],
                        'skuName'           => $skuList["skuName"],
                        'barCode'           => $skuList["barCode"],
                        'orgCountryName'    => $skuList["orgCountryName"],
                        'quantity'          => $skuList["quantity"],
                    ];
                }
            }
        }
        return Normal::returnCode(Normal::SUC,"获取成功",[
            'data'      => $details,
            'has_next'  => $res["data"]["data"]["hasNext"] ?? false
        ]);
    
    }
    /**
     * 加签
     * @param array $param
     */
    protected function getSign( $params = [] )
    {
        $string = '';
        //第一步，排升序
        ksort($params);
        //第二步：keyvalue的格式拼接字符串
        foreach ($params as $key =>$val){
            $string.= $key.$val;
        }
        //第三步：将appsecret拼接在字符串收尾
        $string = $this->config["appsecret"].$string.$this->config["appsecret"];
        //第四步：将字符串转小写
        $string = strtolower($string);
        return md5($string);
    }
    
    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )  
    {
        if( empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method     = $param["method"];
        $url        = $this->config["baseurl"];
        $timestamp  =  time();
        $data = [
            'method'    => $this->RouteMap[$method],
            'appkey'    => $this->config["appkey"],
            'timestamp' => $timestamp,
            'bizcontent'=> $param["data"]
        ];
        $data["sign"] = $this->getSign($data);
        $parameter = [
            [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $data,
                'method'    => 'post',
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
        
            ],
        ];
        if( in_array($method,['queryGoodsList']) ) {
            $resTask = TaskWorker::instance()->addTask($parameter,'handleDiableTask');
        } else {
            $resTask = TaskWorker::instance()->addTask($parameter);
        }
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res,true);
        if( isset($resHttp['success']) && $resHttp['success'] == true ) {
            return Normal::returnCode(Normal::SUC,"操作成功",$resHttp);
        }
        $message = isset($resHttp['msg']) ? $resHttp['msg'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}